package com.bw.servlet;

import com.bw.dao.GoodsDao;
import com.bw.pojo.Goods;
import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/***************************
 FileAction:

 CreateTime:2022-08-03 15:48
 Author:Asking-mac
 ****************************/
@WebServlet("/UpdateServlet")
public class UpdateServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @SneakyThrows
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 先创建smartupload对象
        SmartUpload su = new SmartUpload();
        // 2. 初始化 这个对象
        su.initialize(this.getServletConfig(),request,response);
        // 3. 开启上传  文件进入到  内存中 尚未存入硬盘
        su.upload();
        // 4. 持久化保存到硬盘上
        su.save("/upload");

        // 5. 通过smartupload工具 获取 表单中其它 文本域中的内容
        String id = su.getRequest().getParameter("id");
        String goods_name = su.getRequest().getParameter("goods_name");
        String goods_price = su.getRequest().getParameter("goods_price");
        String goods_des = su.getRequest().getParameter("goods_des");
        String goods_num = su.getRequest().getParameter("goods_num");
        String upload_people = su.getRequest().getParameter("upload_people");

        //String upload_time = su.getRequest().getParameter("upload_time");
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String upload_time = sdf.format(date);

        // 6. 通过smartupload对象 获取所有文件对象
        Files files = su.getFiles();
        // 7. 通过所有文件对象获取第0号位那个文件 因为我们就上传了一个文件  所以只有这个0号位可以使用
        File file = files.getFile(0);
        // 8. 字符串拼接出上传的图片文件在项目中的 相对路径
        String goods_img = "/zy3_yk_fx_war_exploded/upload/" + file.getFileName();
        // 9. 构建商品对象
        Goods goods = new Goods(Integer.parseInt(id), goods_name, Double.parseDouble(goods_price), goods_des, Integer.parseInt(goods_num), upload_people, goods_img, upload_time);
        // 10. 通过dao层存入数据库
        new GoodsDao().updateGoods(goods);
        // 11. 跳转到信息展示页中   我们可以看到 图片也能显示
        request.setAttribute("username",upload_people);
        request.getRequestDispatcher("message.jsp").forward(request,response);
    }
}
